package com.three.crm.page.company;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.amap.api.location.AMapLocation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.three.crm.MyApplication;
import com.three.crm.R;
import com.three.crm.adapter.NinePictureAdapter;
import com.three.crm.alioos.AliyunOSSUploadHelper;
import com.three.crm.base.BaseActivity;
import com.three.crm.bean.AreaBean;
import com.three.crm.bean.CompanyBean;
import com.three.crm.bean.CosTokenBean;
import com.three.crm.bean.FileBean;
import com.three.crm.constant.AppConstant;
import com.three.crm.http.CommonResultCallBack;
import com.three.crm.location.AmapLocationUtil;
import com.three.crm.page.VideoPlayActivity;
import com.three.crm.require.AppRequireService;
import com.three.crm.tencentcloud.BaseConfig;
import com.three.crm.tencentcloud.CosServiceFactory;
import com.three.crm.tencentcloud.CosServiceUtils;
import com.three.crm.util.AppManager;
import com.three.crm.util.GlideEngine;
import com.three.crm.util.GsonUtils;
import com.three.crm.util.LogUtils;
import com.three.crm.util.PercentUtil;
import com.three.crm.util.PictureSelectorUtil;
import com.three.crm.util.SignUtil;
import com.three.crm.util.TString;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 伙伴公司编辑
 * created by lqd on 2024-01-05.
 */
public class CompanyEditActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks{

    private TextView tvTitle,tvProvince,tvCity,tvArea;
    private EditText etCompany,etPhone,etAddress,etLabel,etRemark,etPhone2,etProduction;
    private ImageView ivVideo,ivLogo;
    private FrameLayout flVideo,flLogo;

    public final static String[] PERMISSES = {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    private boolean hasPermiss = false;
    private RecyclerView rvPicture,rvCompany;
    private NinePictureAdapter ninePictureAdapter,companyImgAdapter;
    private int maxSelectPicture = 9;
    private List<FileBean> pictureList = new ArrayList<>();
    private List<FileBean> companyPictureList = new ArrayList<>();

    private TransferManager transferManager;
    private CosServiceUtils serviceUtils;
    private AliyunOSSUploadHelper uploadHelper = null;

    private AmapLocationUtil locationUtil = null;

    private List<AreaBean> provinceBeans,cityBeans,regionBeans;
    private int provinceId = 0,cityId = 0,areaId = 0,currentIndex = 0;
    private int detailId = 0;
    private String latitude = "",longitude = "";
    private CompanyBean bean;
    private String uploadVideoPath = "",logoUrl = "";

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            switch (msg.what){
                case AppConstant.UPLOAD_PROGRESS:
                    long completeCover = bundle.getLong("complete");
                    long targetCover = bundle.getLong("target");
                    showLoading(getString(R.string.progress) + PercentUtil.getPercent(completeCover,targetCover) + "%");
                    break;
                case AppConstant.UPLOAD_COMPLETED:
                    hideLoading();
                    showToast(getString(R.string.upload_success));
                    break;
                case AppConstant.UPLOAD_IMAGE_SUCCESS:
                    hideLoading();
                    showToast(getString(R.string.upload_success));
                    String tempUrl = bundle.getString(AppConstant.IMAGE_PATH);
                    Log.i("TAG","tempUrl="+tempUrl);
                    handleImg(tempUrl);
                    break;
                case AppConstant.UPLOAD_FAIL:
                    hideLoading();
                   // showToast(getString(R.string.upload_fail));
                    break;
                case AppConstant.UPLOAD_VIDEO_SUCCESS:
                    hideLoading();
                    showToast(getString(R.string.upload_success));
                    uploadVideoPath = bundle.getString(AppConstant.VIDEO_PATH);
                    handleVideo();
                    break;
                case AppConstant.UPLOAD_COVER_SUCCESS:
                    hideLoading();
                    showToast(getString(R.string.upload_success));
                    //logoUrl = bundle.getString(AppConstant.COVER_PATH);
                    String tempUrl2 = bundle.getString(AppConstant.COVER_PATH);
                    handleCompanyImg(tempUrl2);
                    break;
            }
        }
    };

    private void handleVideo() {
        if (TextUtils.isEmpty(uploadVideoPath)) {
            flVideo.setVisibility(View.GONE);
        } else {
            flVideo.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(uploadVideoPath)
                    .centerCrop()
                    .placeholder(R.mipmap.ic_default_image)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(ivVideo);
        }
    }

    private void handleCompanyImg(String tempUrl) {
        FileBean bean = new FileBean();
        bean.setUrl(tempUrl);
        companyPictureList.add(bean);
        companyImgAdapter.setNewData(companyPictureList);
    }

    private void handleImg(String tempUrl) {
        FileBean bean = new FileBean();
        bean.setUrl(tempUrl);
        pictureList.add(bean);
        ninePictureAdapter.setNewData(pictureList);
    }

    @Override
    protected void initParms(Bundle bundle) {
        if (bundle != null) {
            bean = bundle.getParcelable(AppConstant.EXTRAS_DATA);
        }
    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_company_edit;
    }

    @Override
    protected void initViews(View view, Bundle savedInstanceState) {
        initLocation();
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK) {
                    CompanyBean companyBean = (CompanyBean) result.getData().getExtras().get(AppConstant.EXTRAS_BEAN);
                    if (companyBean != null) {
                        etAddress.setText(companyBean.getAddress());
                        latitude = companyBean.getLatitude();
                        longitude = companyBean.getLongitude();
                    }
                }
            }
        });
        onCheckPermission();
        tvTitle = $(R.id.tv_title);
        tvTitle.setText(R.string.form_add);

        etCompany = $(R.id.et_customer);
        etPhone = $(R.id.et_phone);

        etAddress = $(R.id.et_address);
        etLabel = $(R.id.et_label);
        etRemark = $(R.id.et_remark);
        tvProvince = $(R.id.tv_province);
        tvCity = $(R.id.tv_city);
        tvArea = $(R.id.tv_area);

        ivVideo = $(R.id.iv_video);
        flVideo = $(R.id.fl_video);
        ivLogo = $(R.id.iv_logo);
        flLogo = $(R.id.fl_logo);
        etPhone2 = $(R.id.et_phone2);
        etProduction = $(R.id.et_production);

        rvPicture = $(R.id.rv_picture);
        GridLayoutManager layoutManager = new GridLayoutManager(this,3);
        rvPicture.setLayoutManager(layoutManager);
        ninePictureAdapter = new NinePictureAdapter();
        ninePictureAdapter.setType("");
        rvPicture.setAdapter(ninePictureAdapter);

        rvCompany = $(R.id.rv_picture_company);
        GridLayoutManager layoutManager2 = new GridLayoutManager(this,3);
        rvCompany.setLayoutManager(layoutManager2);
        companyImgAdapter = new NinePictureAdapter();
        companyImgAdapter.setType("");
        rvCompany.setAdapter(companyImgAdapter);

        if (bean != null) {
            tvTitle.setText(R.string.form_edit);
            longitude = bean.getLongitude();
            latitude = bean.getLatitude();
            detailId = bean.getId();
            etCompany.setText(bean.getTitle());
            etRemark.setText(bean.getContent());
            etAddress.setText(bean.getAddress());
            etPhone.setText(bean.getPhone());
            etLabel.setText(bean.getLabel());
            etPhone2.setText(bean.getPhone2());
            etProduction.setText(bean.getMonth_production());

           // logoUrl = bean.getLogo();
           // handleLogo();
            String logoArr = bean.getLogo();
            String[] logos = logoArr.split(",");
            if (logos != null && logos.length > 0) {
                for (int i = 0; i < logos.length; i++) {
                    String url = logos[i];
                    FileBean bean = new FileBean();
                    bean.setUrl(url);
                    companyPictureList.add(bean);
                }
                companyImgAdapter.setNewData(companyPictureList);
            }

            uploadVideoPath = bean.getVideo_url();
            handleVideo();

            queryDetail();

            String imgArr = bean.getImages();
            String[] imgs = imgArr.split(",");
            if (imgs != null && imgs.length > 0) {
                for (int i = 0; i < imgs.length; i++) {
                    String url = imgs[i];
                    FileBean bean = new FileBean();
                    bean.setUrl(url);
                    pictureList.add(bean);
                }
                ninePictureAdapter.setNewData(pictureList);
            }
        } else {
            startLocation();
        }

    }

    private void queryDetail() {
        if (detailId != 0) {
            showLoading(getString(R.string.loading));

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("userToken", AppManager.getToken());
                jsonObject.put("company_id",detailId);
                jsonObject.put("timestamp",getTimestamp());
                String sign = SignUtil.genSign(jsonObject);
                jsonObject.put("sign",sign);
                AppRequireService.queryCompanyDetail(this, AppConstant.QUERY_DETAIL, jsonObject, new CommonResultCallBack(this) {
                    @Override
                    public void onResult(String result, int requireCode) {
                        Log.i("TAG","result="+result);
                        hideLoading();
                        if (requireCode == AppConstant.QUERY_DETAIL) {
                            CompanyBean bean = GsonUtils.parseJsonWithGson(result, CompanyBean.class);
                            setDetail(bean);
                        }
                    }

                    @Override
                    public void onConnectTimeOut(Call call, Exception e, int requireCode) {
                        hideLoading();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onFail(String msg, int requireCode) {
                        hideLoading();
                        showToast(msg);
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void setDetail(CompanyBean bean) {
        if (bean != null) {
            provinceId = bean.getProvince_id();
            cityId = bean.getCity_id();
            areaId = bean.getArea_id();
            //queryAreaByCode(provinceId);
            tvArea.setText(bean.getArea());
            tvProvince.setText(bean.getProvince());
            tvCity.setText(bean.getCity());
        }
    }

    private void initLocation() {
        if (locationUtil == null) {
            locationUtil = new AmapLocationUtil(getApplicationContext());
        }
        locationUtil.initLocation();
        locationUtil.setOnCallBackListener(new AmapLocationUtil.onCallBackListener() {
            @Override
            public void onCallBack(double mlongitude, double mlatitude, AMapLocation location, boolean isSucdess, String address) {
                LogUtils.onUploadLog("定位信息：" + location.toString());
                if (isSucdess){
                    latitude = String.valueOf(mlatitude);//获取纬度
                    longitude = String.valueOf(mlongitude);//获取经度
                    etAddress.setText("" + location.getAddress() + location.getDescription() + location.getStreet() + location.getStreetNum());
                    tvProvince.setText(location.getProvince());
                    tvCity.setText(location.getCity());
                    tvArea.setText(location.getDistrict());
                    hideLoading();
                } else {
                    showToast("定位失败，请重新定位!");
                }
            }
        });
    }

    private void startLocation() {
        if (hasPermiss && locationUtil != null) {
            locationUtil.startLocation();
            showLoading(getString(R.string.locationing));
        }
    }

    private void onCheckPermission() {
        if (EasyPermissions.hasPermissions(this,PERMISSES)){
            hasPermiss = true;
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.app_name) + "需要使用相机、手机存储、定位等权限，您是否同意?",
                    AppConstant.RC_PERMISSES, PERMISSES);
        }
    }

    @Override
    protected void setListener() {
        $(R.id.iv_left).setOnClickListener(this);
        $(R.id.ll_province).setOnClickListener(this);
        $(R.id.ll_city).setOnClickListener(this);
        $(R.id.ll_area).setOnClickListener(this);

        $(R.id.btn_submit).setOnClickListener(this);
        $(R.id.iv_take_picture).setOnClickListener(this);
        $(R.id.iv_take_video).setOnClickListener(this);
        $(R.id.iv_take_logo).setOnClickListener(this);
        $(R.id.iv_search_location).setOnClickListener(this);
        $(R.id.fl_video).setOnClickListener(this);
        ninePictureAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                FileBean bean = (FileBean) baseQuickAdapter.getItem(position);
                String imgUrl = bean.getUrl();
                switch (view.getId()){
                    case R.id.iv_delete:
                        deleteByPath(imgUrl);
                        break;
                }
            }
        });
        companyImgAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                FileBean bean = (FileBean) baseQuickAdapter.getItem(position);
                String imgUrl = bean.getUrl();
                switch (view.getId()){
                    case R.id.iv_delete:
                        deleteCompanyByPath(imgUrl);
                        break;
                }
            }
        });
    }

    private void deleteCompanyByPath(String path) {
        int selectPos = -1;
        for (int i = 0; i < companyPictureList.size(); i++) {
            FileBean bean = companyPictureList.get(i);
            if (path.equals(bean.getUrl())) {
                selectPos = i;
                break;
            }
        }
        companyPictureList.remove(selectPos);
        companyImgAdapter.setNewData(companyPictureList);
    }

    private void deleteByPath(String path){
        int selectPos = -1;
        for (int i = 0; i < pictureList.size(); i++) {
            FileBean bean = pictureList.get(i);
            if (path.equals(bean.getUrl())) {
                selectPos = i;
                break;
            }
        }
        pictureList.remove(selectPos);
        ninePictureAdapter.setNewData(pictureList);
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()){
            case R.id.iv_left:
                finish();
                break;
            case R.id.ll_province:
                //showDialogFragment(0,provinceBeans);
                break;
            case R.id.ll_city:
//                if (provinceId == 0) {
//                    showToast("请先选择省/地区");
//                } else {
//                    currentIndex = 1;
//                    queryAreaByCode(provinceId);
//                }
                break;
            case R.id.ll_area:
//                if (cityId == 0) {
//                    showToast("请选择市");
//                } else {
//                    currentIndex = 2;
//                    queryAreaByCode(cityId);
//                }
                break;
            case R.id.iv_take_picture:
                if (hasPermiss) {
                    if (pictureList.size() == maxSelectPicture) {
                        showToast("最多只能上传9张图片");
                    } else {
                        onTakePicture();
                    }
                } else {
                    onCheckPermission();
                }
                break;
            case R.id.iv_take_video:
                if (hasPermiss) {
                    onTakeVideo();
                } else {
                    onCheckPermission();
                }
                break;
            case R.id.iv_take_logo:
                if (hasPermiss) {
                    onTakeLogo();
                } else {
                    onCheckPermission();
                }
                break;
            case R.id.btn_submit:
                onSubmit();
                break;
            case R.id.iv_search_location:
                onSearchLocation();
                break;
            case R.id.fl_video:
                onPlayVideo();
                break;
        }
    }

    private void onPlayVideo() {
        if (TextUtils.isEmpty(uploadVideoPath)) {
            showToast("视频不存在了");
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.VIDEO_PATH,uploadVideoPath);
        startActivity(VideoPlayActivity.class,bundle);
    }

    private void onTakeVideo() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofVideo())
//                .openGallery(SelectMimeType.ofVideo())
//                .setMaxSelectNum(1)
//                .setSelectorUIStyle(PictureSelectorUtil.getSelectorStyle(this))
//                .setSelectionMode(SelectModeConfig.SINGLE)
//                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        LocalMedia media = result.get(0);
                        uploadFile(media,"video");
                    }

                    @Override
                    public void onCancel() {
                        showToast("您取消了选择视频的操作");
                    }
                });
    }

    private void uploadFile(LocalMedia media,String index) {
        showLoading(getString(R.string.uploading));
        int successCode = AppConstant.UPLOAD_IMAGE_SUCCESS;
        String successPath = AppConstant.IMAGE_PATH;
        if (index.equals("video")) {
            successCode = AppConstant.UPLOAD_VIDEO_SUCCESS;
            successPath = AppConstant.VIDEO_PATH;
        } else if (index.equals("order")) {
            successCode = AppConstant.UPLOAD_COVER_SUCCESS;
            successPath = AppConstant.COVER_PATH;
        }
        int finalSuccessCode = successCode;
        String finalSuccessPath = successPath;
        uploadHelper.uploadFile(media.getRealPath(),media.getMimeType(),media.getFileName(), new AliyunOSSUploadHelper.OSSCallback() {
            @Override
            public void onProgress(long complete, long target,String url) {
                Message message = new Message();
                Bundle bundle = new Bundle();
                message.what = AppConstant.UPLOAD_PROGRESS;
                bundle.putLong("complete",complete);
                bundle.putLong("target",target);
                message.setData(bundle);
                handler.sendMessage(message);
            }

            @Override
            public void onSuccess(String url) {
                Message message = new Message();
                message.what = finalSuccessCode;
                Bundle bundle = new Bundle();
                bundle.putString(finalSuccessPath,url);
                message.setData(bundle);
                handler.sendMessage(message);
            }

            @Override
            public void onFailure(ClientException clientExcepion, ServiceException serviceException) {
                Message message = new Message();
                message.what = AppConstant.UPLOAD_FAIL;
                handler.sendMessage(message);
            }
        });
//        serviceUtils.uploadFile(this, media.getRealPath(), media.getFileName(), media.getMimeType(), new CosServiceUtils.UpLoadCallBack() {
//            @Override
//            public void onProgress(long complete, long target) {
//                Message message = new Message();
//                message.what = AppConstant.UPLOAD_PROGRESS;
//                Bundle bundle = new Bundle();
//                bundle.putLong("complete",complete);
//                bundle.putLong("target",target);
//                message.setData(bundle);
//                handler.sendMessage(message);
//            }
//
//            @Override
//            public void onStatusChange(TransferState state) {
//                if (state == TransferState.COMPLETED) {
//                    Message message = new Message();
//                    message.what = AppConstant.UPLOAD_COMPLETED;
//                    handler.sendMessage(message);
//                }
//            }
//
//            @Override
//            public void onSuccess(String url) {
//                Message message = new Message();
//                message.what = finalSuccessCode;
//                Bundle bundle = new Bundle();
//                bundle.putString(finalSuccessPath,url);
//                message.setData(bundle);
//                handler.sendMessage(message);
//            }
//
//            @Override
//            public void onFail() {
//                Message message = new Message();
//                message.what = AppConstant.UPLOAD_FAIL;
//                handler.sendMessage(message);
//            }
//        });
    }

    private void onTakeLogo() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofImage())
//                .openGallery(SelectMimeType.ofImage())
//                .setMaxSelectNum(1)
//                .setSelectorUIStyle(PictureSelectorUtil.getSelectorStyle(this))
//                .setSelectionMode(SelectModeConfig.SINGLE)
//                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        handleLogoList(result);
                    }

                    @Override
                    public void onCancel() {
                        showToast("您取消了选择");
                    }
                });
    }

    private void onSearchLocation() {
       // Intent intent = new Intent(this, SearchLocationActivity.class);
       // intentActivityResultLauncher.launch(intent);
        startLocation();
    }

    private void showDialogFragment(int index,List<AreaBean> mList) {
        if (TString.isEmpty(mList)) {
            showToast("暂无数据");
        } else {
            String title = "请选择省/地区";
            if (index == 0) {
                title = "请选择省/地区";
            } else if (index == 1) {
                title = "请选择市";
            } else if (index == 2){
                title = "请选择区/县";
            }
            String items[] = new String[mList.size()];
            for (int i = 0; i < mList.size(); i++) {
                AreaBean bean = mList.get(i);
                items[i] = bean.getName();
            }
            new XPopup.Builder(this)
                    // .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .maxHeight(MyApplication.getPopupHeight())
                    .asBottomList(title, items,
                            null,
                            new OnSelectListener() {
                                @Override
                                public void onSelect(int position, String text) {
                                    if (index == 0) {
                                        tvProvince.setText(text);
                                        provinceId = provinceBeans.get(position).getId();

                                        tvCity.setText("市");
                                        cityId = 0;
                                        tvArea.setText("区/县");
                                        areaId = 0;
                                        cityBeans.clear();
                                        regionBeans.clear();

                                    } else if (index == 1) {
                                        tvCity.setText(text);
                                        cityId = cityBeans.get(position).getId();
                                        currentIndex = 2;
                                        tvArea.setText("区/县");
                                        areaId = 0;
                                        regionBeans.clear();

                                    } else if (index == 2){
                                        tvArea.setText(text);
                                        areaId = regionBeans.get(position).getId();
                                    }
                                }
                            })
                    .show();
        }
    }

    private void onTakePicture() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofImage())
//                .openGallery(SelectMimeType.ofImage())
//                .setMaxSelectNum(maxSelectPicture - pictureList.size())
//                .setSelectorUIStyle(PictureSelectorUtil.getSelectorStyle(this))
//                .setSelectionMode(SelectModeConfig.MULTIPLE)
//                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        handlePictureList(result);
                    }

                    @Override
                    public void onCancel() {
                        showToast("您取消了选择");
                    }
                });
    }

    private void onSubmit() {
        String company = etCompany.getText().toString();
        if (TextUtils.isEmpty(company)) {
            showToast("请填写供应商名称");
            etCompany.requestFocus();
            return;
        }
        String phone = etPhone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            showToast("请填写供应商联系电话");
            etPhone.requestFocus();
            return;
        }
        String phone2 = etPhone2.getText().toString();
        String production = etProduction.getText().toString();
        if (TextUtils.isEmpty(production)) {
            showToast("请填写公司月产能");
            etProduction.requestFocus();
            return;
        }
        String provinceName = tvProvince.getText().toString();
//        if (TextUtils.isEmpty(provinceName)) {
//            showToast("请重新定位");
//            return;
//        }
        String cityName = tvCity.getText().toString();
//        if (TextUtils.isEmpty(cityName)) {
//           // showToast("请选择客户所在市/县");
//            showToast("请重新定位");
//            return;
//        }
        String areaName = tvArea.getText().toString();
//        if (TextUtils.isEmpty(areaName)) {
//            //showToast("请选择客户所在区/镇/街道");
//            showToast("请重新定位");
//            return;
//        }
        String address = etAddress.getText().toString();
        if (TextUtils.isEmpty(address)) {
            showToast("请填写客户详情地址");
            etAddress.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(latitude) || TextUtils.isEmpty(longitude)) {
            showToast("获取位置信息异常,请重新定位！");
            return;
        }
        if (pictureList.size() == 0) {
            showToast("请上传产品照片");
            return;
        }
//        if (companyPictureList.size() == 0) {
//            showToast("请上传公司照片");
//            return;
//        }
        String label = etLabel.getText().toString();
//        if (TextUtils.isEmpty(label)) {
//            showToast("请填写公司标签");
//            etLabel.requestFocus();
//            return;
//        }
        String remark = etRemark.getText().toString();
//        if (TextUtils.isEmpty(remark)) {
//            showToast("请填写备注");
//            etRemark.requestFocus();
//            return;
//        }
        showLoading(getString(R.string.submitting));
        JSONObject jsonObject = new JSONObject();

        String files = "";
        int fileSize = pictureList.size();
        if (fileSize > 0) {
            for (int i = 0; i < fileSize; i++) {
                FileBean bean = pictureList.get(i);
                files += bean.getUrl();
                if (fileSize - 1 != i) {
                    files += ",";
                }
            }
        }

        String logofiles = "";
        int logofileSize = companyPictureList.size();
        if (logofileSize > 0) {
            for (int i = 0; i < logofileSize; i++) {
                FileBean bean = companyPictureList.get(i);
                logofiles += bean.getUrl();
                if (logofileSize - 1 != i) {
                    logofiles += ",";
                }
            }
        }

        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("title",company);
            jsonObject.put("phone",phone);
            jsonObject.put("phone2",phone2);
            jsonObject.put("logo",logofiles);
            jsonObject.put("video_url",uploadVideoPath);
            jsonObject.put("month_production",production);
            jsonObject.put("province_id",provinceName);
            jsonObject.put("city_id",cityName);
            jsonObject.put("area_id",areaName);
            jsonObject.put("content",remark);
            jsonObject.put("images",files);
            jsonObject.put("label",label);
            jsonObject.put("address",address);
            jsonObject.put("latitude",latitude);
            jsonObject.put("longitude",longitude);
            jsonObject.put("id",detailId);
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.companyEdit(this,AppConstant.FORM_SUBMIT,jsonObject,callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void initData(Context mContext) {
        initCosToken();
        provinceBeans = new ArrayList<>();
        cityBeans = new ArrayList<>();
        regionBeans = new ArrayList<>();
        currentIndex = 0;
        queryAreaByCode(0);
    }

    private void queryAreaByCode(int code) {
        showLoading(getString(R.string.loading));
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("parent_id",code);
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.queryArea(this,AppConstant.QUERY_LIST,jsonObject,callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void handleLogoList(ArrayList<LocalMedia> result) {
        for (int i = 0; i < result.size(); i++) {
            LocalMedia localMedia = result.get(i);
            uploadFile(localMedia,"order");
        }
    }

    private void handlePictureList(ArrayList<LocalMedia> result) {
        for (int i = 0; i < result.size(); i++) {
            LocalMedia localMedia = result.get(i);
            uploadFile(localMedia,"image");
        }
    }

    private void initCosToken() {
        showLoading(getString(R.string.loading));
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.getCosConfig(this,AppConstant.QUERY_TOKEN,jsonObject,callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private CommonResultCallBack callBack = new CommonResultCallBack(this) {
        @Override
        public void onResult(String result, int requireCode) {
            hideLoading();
            if (requireCode == AppConstant.QUERY_TOKEN) {
                if (result != null) {
                    CosTokenBean bean = GsonUtils.parseJsonWithGson(result, CosTokenBean.class);
                    initFileWithCosService(bean);
                }
            } else if (requireCode == AppConstant.QUERY_LIST) {
                if (currentIndex == 0) {
                    provinceBeans = GsonUtils.parseJsonArrayWithGson(result,AreaBean.class);
                } else if (currentIndex == 1) {
                    cityBeans = GsonUtils.parseJsonArrayWithGson(result,AreaBean.class);
                    showDialogFragment(1,cityBeans);
                } else if (currentIndex == 2) {
                    regionBeans = GsonUtils.parseJsonArrayWithGson(result,AreaBean.class);
                    showDialogFragment(2,regionBeans);
                }
            } else if (requireCode == AppConstant.FORM_SUBMIT) {
                AppManager.setNeedUpdate(true);
                showToast("操作成功");
                finish();
            }
        }

        @Override
        public void onConnectTimeOut(Call call, Exception e, int requireCode) {
            showToast(e.getMessage());
            hideLoading();
        }

        @Override
        public void onFail(String msg, int requireCode) {
            showToast(msg);
            hideLoading();
        }
    };

    private void initFileWithCosService(CosTokenBean bean) {
//        transferManager = CosServiceFactory.getTransferManager(this, BaseConfig.REGION,BaseConfig.SECRETID,BaseConfig.SECRETKEY,bean.getToken(),bean.getStartTime(),bean.getExpirationAt(),true);
//        serviceUtils = new CosServiceUtils(transferManager);
        uploadHelper = new AliyunOSSUploadHelper(this,bean.getBucket(),bean.getEndpoint(),bean.getAccessKeyId(),bean.getAccessKeySecret(),bean.getSecurityToken());
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        hasPermiss = true;
        startLocation();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {

    }

    @Override
    public void onRationaleDenied(int requestCode) {
        showToast("好伤心，您将无法使用定位等相关功能");
    }



    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationUtil != null) {
            locationUtil.stopLocation();
        }
        hideLoading();
    }
}